import { UploadOutlined } from "@ant-design/icons";
import { Button, Input, Upload, message } from "antd";
import { useState } from "react";

export default () => {
    const [fileName, setFileName] = useState("");
    const [imageBase64, setImageBase64] = useState("");

    const props = {
        beforeUpload: (file) => {
            setFileName(file.name);
            if (typeof FileReader == "undifined") {
                //判断浏览器是否支持filereader
                message.warn("抱歉，你的浏览器不支持 FileReader");
                return false;
            }
            if (!/image\/\w+/.test(file.type)) {
                //判断获取的是否为图片文件
                message.warn("请确保文件为图像文件");
                return false;
            }
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                setImageBase64(this.result);
                var result = document.getElementById("result");
                result.innerHTML = '<img src="' + this.result + '" alt=""/>';
            };
            return false;
        },
        fileList: [],
    };

    return (
        <div>
            <Upload {...props} accept=".png,.jpg,.gif">
                <Button icon={<UploadOutlined />}>选择图片文件</Button>
                <span style={{ paddingLeft: 20 }}>{fileName}</span>
            </Upload>
            <div style={{ marginTop: 10 }}>
                BASE64（img标签）:
                <Input.TextArea value={imageBase64} style={{ width: "100%", height: 200 }} />
            </div>
            <div name="result" id="result"></div>
        </div>
    );
};
